from urllib import request
import json
from urllib.request import Request
from urllib import parse
# # 1.分析请求url
# url = "http://httpbin.org/get?name=qiku"
# # 2.发起请求
# response = request.urlopen(url)
# # 3.解析数据 get
# if response.status == 200:
#     response_bytes = response.read()
#     response_text = response_bytes.decode('utf-8')
#     response_json = json.loads(response_text)
#     print(response_json['headers']['User-Agent'],response_json['args'])




# # 1.分析请求url
#
# data = {'name':'qiku','age':10,'addr':'金水'}
# url_encode = parse.urlencode(data)
# print(url_encode)
#
# url = f"http://httpbin.org/get?{url_encode}"

# 1.2 构建请求实例
# req = Request(url,headers={
# 'user-agent':
# 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1'
# },method='GET')
#
# # 2.发起请求 get
# response = request.urlopen(req)
# # 3.解析数据
# if response.status == 200:
#     response_bytes = response.read()
#     response_text = response_bytes.decode('utf-8')
#     response_json = json.loads(response_text)
#     print(response_json['headers']['User-Agent'],response_json['args'])



# # 1.分析请求url
# url = "http://httpbin.org/post?name=qiku"
#
#
# #'content-type':'application/x-www-form-urlencoded',
# data = {'age':10,'addr':'金水'}
# url_encode = parse.urlencode(data)
#
#
# # 1.2 构建请求实例
# req = Request(url,data=url_encode.encode(), headers={
# 'user-agent':
# 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1',
#
# # 默认请求参数的类型form
# # 'content-type':'application/x-www-form-urlencoded',
#
# },method='POST')
# # 2.发起请求 get
# response = request.urlopen(req)
# # 3.解析数据
# if response.status == 200:
#     response_bytes = response.read()
#     response_text = response_bytes.decode('utf-8')
#     response_json = json.loads(response_text)
#     print(response_json,response_json['headers']['User-Agent'],response_json['args'])





# 1.分析请求url
url = "http://httpbin.org/post?name=qiku"


#'content-type':'application/x-www-form-urlencoded',
data = {'age':10,'addr':'金水'}
json_encode = json.dumps(data)


# 1.2 构建请求实例
req = Request(url,data=json_encode.encode(), headers={
'user-agent':
'Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1',

# 更改请求参数的类型json
'content-type':'application/json',

},method='POST')
# 2.发起请求 get
response = request.urlopen(req)
# 3.解析数据
if response.status == 200:
    response_bytes = response.read()
    response_text = response_bytes.decode('utf-8')
    response_json = json.loads(response_text)
    print(response_json,response_json['headers']['User-Agent'],response_json['args'])




